#pragma once
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<iostream>

#include<string>

class TcpSocket
{
private:
    int fd_;
public:
    TcpSocket():fd_(-1){}
    TcpSocket(int fd):fd_(fd){}
    int GetFD()
    {
        return fd_;
    }
    bool CreateSocket()
    {
        fd_ = socket(AF_INET,SOCK_STREAM,0);
        if(fd_ < 0)
            return false;
        return true;
    }
    bool Bind(const std::string& ip,int port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());

        int bind_fd = bind(fd_,(struct sockaddr*)&addr,sizeof(addr));
        if(bind_fd < 0)
            return false;
        return true;
    }
    bool Listen(int num)
    {
        if(listen(fd_,num) != 0)
            return false;
        return true;
    }
    bool Accept(TcpSocket& dest,std::string& ip,int& port)
    {
        struct sockaddr_in dest_addr;
        socklen_t len = sizeof(dest_addr);
        int new_fd = accept(fd_,(struct sockaddr*)&dest_addr,&len);

        if(new_fd < 0)
            return false;

        dest.fd_ = new_fd;
        
        ip = std::string(inet_ntoa(dest_addr.sin_addr));
        port = ntohs(dest_addr.sin_port);
        std::cout << ip << ":" << port << std::endl;
        return true;
    }
    bool Recv(void* data,int size)
    {
        recv(fd_,data,size,0);
        return true;
    }
    bool Send(void* data,int size)
    {
        send(fd_,data,size,0);
        return true;
    }
    bool Connect(const std::string& ip,int port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        
        if(connect(fd_,(struct sockaddr*)&addr,sizeof(addr)) != 0)
            return false;
        return true;
    }
};